# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/25 15:32
# File: craft.py
# IDE: PyCharm

from rest_framework.viewsets import GenericViewSet
from serializers.craft import CraftSerializer
from models.craft import Craft
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from utils.response.response import BaseResponse
from utils.Decorators.webworkdecorator import WorkDecorator
from utils.response.httpstate import *
from rest_framework import status
from utils.pagination import pagination,pageSerializer
from filters.craft import CraftFilter

class CraftViewSet(GenericViewSet):

    queryset = Craft.objects.filter(is_delete=0)
    serializer_class = CraftSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    pagination_class =pagination.Pagination
    filter_class = CraftFilter
    search_fields = ('title','craft_category')

    @WorkDecorator(operate="工艺标准", message='列表')
    def list(self, request,*args,**kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page_queryset = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_queryset, many=True)
        count = self.paginator.page.paginator.count  # 总数
        num = self.paginator.page.paginator.num_pages  # 页数
        page_size = self.paginator.get_page_size(request)  # 每页显示条数
        pageserializer = pageSerializer.Serializer({'count': count, 'page_num': num, 'page_size': page_size})

        return BaseResponse(data=serializer.data,page=pageserializer.data)

    @WorkDecorator(operate="工艺标准", message='新增')
    def create(self, request,*args,**kwargs):

        data = request.data
        # 2.创建序列化器
        serializer = self.get_serializer(data=data)
        # 3.校验
        serializer.is_valid(raise_exception=True)
        # 4.保存
        serializer.save()
        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="工艺标准", message='详情')
    def retrieve(self, request, pk,*args, **kwargs):

        object = Craft.objects.filter(pk=pk).first()

        object.read_count+=1
        object.save()
        serializer = self.get_serializer(object)


        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="工艺标准", message='更新')
    def update(self, request,pk,*args,**kwargs):

        object = Craft.objects.filter(pk=pk).first()
        object_ser = CraftSerializer(object, data=request.data)

        if object_ser.is_valid():
            object_ser.save()
            return BaseResponse()
        else:
            return BaseResponse(message='错误', code=CODE_BUSSINESS_ERROR)
        # 5.返回响应

    @WorkDecorator(operate="工艺标准", message='删除')
    def destroy(self, request, pk, *args, **kwargs):

        object = Craft.objects.filter(pk=pk).first()
        object.is_delete = 1
        object.save()
        return BaseResponse()
